/*
 * @lc app=leetcode.cn id=637 lang=typescript
 *
 * [637] 二叉树的层平均值
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function averageOfLevels(root: TreeNode | null): number[] {
    const cache: number[][] = [[]];
    const tre = (root: TreeNode | null, deep: number) => {
        if (!root) return;
        if (root.left) {
            tre(root.left, deep + 1);
        }
        if (root.right) {
            tre(root.right, deep + 1);
        }
        if (cache[deep]) {
            cache[deep].push(root.val);
        } else {
            cache[deep] = [root.val];
        }
    };
    tre(root, 0);
    return cache.map((i) => {
        return i.reduce((a, b) => a + b, 0) / i.length;
    });
}

// @lc code=end
